<template>
    <div class="MainLayoutArea"  style="width: 100%;height: 100%; display: flex;flex-direction: column;">


<!--    博客标题以及相关标签展示-->
        <div style="width: 100%;padding-bottom: 10px;">
            <el-card class="button-card"
                     :body-style="bodyStyle">

                <el-row type="flex"   justify="space-around">
                    <el-col :span="4"><div class="grid-content bg-purple"></div></el-col>
                    <el-col :span="16" style="text-align: center">
                        <span style="font-size: large" >{{blog.title}}</span>
                    </el-col>
                    <el-col :span="4" style="color: #7773737d;">
                        <i class="el-icon-view">{{blogHitsNum}}</i> &nbsp;
                        <i class="el-icon-thumb">{{blog.likeCount}}</i>
                    </el-col>
                </el-row>
                <el-row type="flex"   justify="space-around">
                    <el-col :span="4">
                    </el-col>
                    <el-col :span="16" style="text-align: center">
                        <div class="labelLayout" >
                            <div v-for="(label,index) in blog.labels" :key="label.id" style="margin:0 5px;display: inline-block;">
                                <el-tag v-if="index==0"  class="myTag" @click="queryBlog(label)">
                                    {{label.content}}
                                </el-tag>
                                <el-tag v-if="index==1"  type="success" class="myTag" @click="queryBlog(label)">
                                    {{label.content}}
                                </el-tag>
                                <el-tag v-if="index==2" type="info" class="myTag" @click="queryBlog(label)">
                                    {{label.content}}
                                </el-tag>
                                <el-tag v-if="index==3" type="warning" class="myTag" @click="queryBlog(label)">
                                    {{label.content}}
                                </el-tag>
                                <el-tag v-if="index==4" type="danger" class="myTag" @click="queryBlog(label)">
                                    {{label.content}}
                                </el-tag>
                                <el-tag v-else-if="index==5" type="info" class="myTag" @click="toShowAllLabelsDialog(blog)">
                                    <span >...</span>
                                </el-tag>
                                <el-tag v-else  style="display: none" ></el-tag>
                            </div>
                        </div>
                    </el-col>
                    <el-col :span="4">
                        <el-button v-if="currentUser.role==role_admin" type="info" size="mini" @click="toBlogUpdateView">编辑</el-button>
                        <el-button type="info" size="mini" @click="updateMenuStatus">{{viewMenuTitle}}</el-button>
                    </el-col>
                </el-row>

            </el-card>
        </div>

<!--        博客展示区域-->
        <div class="blogMainArea"  >
            <mavon-editor
                    class="editorStyle"
                    v-model="blog.content"
                    :subfield="false"
                    :boxShadow="false"

                    :navigation="navigation"
                    :scrollStyle="true"
                    defaultOpen="preview"
                    :toolbarsFlag="false"
                    :ishljs="true">

            </mavon-editor>
        </div>

<!--        所有标签展示框-->
        <el-dialog
                :title="dialogTitle"
                :visible.sync="dialogVisible"
                @navigationToggle="xxx"
                width="60%"
                @close="dialogBlogLabels=[]"
                :modal-append-to-body="false"
                :append-to-body="true"
                :show-close="false"
                center>
            <template slot="title">

                <el-row style="width: 100%">
                    <el-col :span="8">
                        &nbsp;
                    </el-col>
                    <!--                    标题显示-->
                    <el-col :span="8" style="text-align: center;font-size: 20px">
                        <span>{{dialogTitle}}</span>
                    </el-col>
                    <!--                    右上角按钮-->
                    <el-col :span="8">
                        &nbsp;
                    </el-col>
                </el-row>

            </template>

            <!--            查看所有标签-->
            <div v-if="dialogTitle=='查看所有标签'">

                <el-card class="box-card" style="margin-bottom: 10px">
                    <el-table
                            :data="dialogBlogLabels"
                            style="width: 100%;margin-bottom: 20px;min-height: 400px;"
                            row-key="id"
                            height="400">
                        <el-table-column
                                prop="content"
                                label="内容">
                        </el-table-column>
                        <el-table-column
                                prop="createTime"
                                label="发布时间"
                                sortable>
                            <template slot-scope="scope">
                                {{scope.row.createTime | dateFormatFun(2)}}
                            </template>
                        </el-table-column>
                        <el-table-column
                                label="操作">
                            <template slot-scope="scope">
                                <el-button type="info" @click="queryBlog(scope.row),dialogVisible = false">查询</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-card>

                <div>
                    <el-card class="box-card" style="text-align: center">
                        <el-button @click="dialogVisible = false">取 消</el-button>
                        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
                    </el-card>
                </div>
            </div>

        </el-dialog>





    </div>


</template>

<script>
    import { mavonEditor } from 'mavon-editor'          //引入markdown编辑器
    import 'mavon-editor/dist/css/index.css'            //引入markdown编辑器相关样式
    import Clipboard from "clipboard"                  //引入剪切板复制类
    import {constants} from "@/common/constants"

    export default {
        name: "BlogView",
        components:{
            mavonEditor,
        },
        data(){
            return{
                queryBlogId : Number,       //查询的博客id
                blog:{},                    //正在展示的博客信息
                navigation:true,           //是否显示目录
                bodyStyle:{                 //card的body样式
                    padding: '10px' ,
                    lineHeight: '40px',
                },
                viewMenuTitle: "关闭导航栏",     //提示是否关闭博客的导航栏界面
                dialogTitle:"",                 //根据dialog标题显示dialog内容
                dialogVisible: false,           //新增博客弹出框是否展示
                dialogBlogLabels:[],            //查看所有标签的对话框的label数组
                blogHitsNum:"",              //博客点击量
                currentUser:(localStorage.getItem("user")!=null)?JSON.parse(localStorage.getItem("user")):null,   //当前登录的用户
                role_admin:constants.role.admin,    //admin角色
            }
        },
        created() {
            this.queryBlogId=this.$route.query.id;
            // this.$emit('watchBlogView');
            this.queryBlogById();
            this.addHitsNum();
            this.addOrUpdateHistory();
        },
        mounted() {
            this.listenMavonEditorMenuClose();
            this.updateMenuStatus();
        },
        methods:{
            //跳转到编辑界面
            toBlogUpdateView(){
                this.$router.push({
                    path:"/backendFramework/blog",
                    query:{blogId: this.queryBlogId}},
                );
            },
            //添加监听事件，监听目录的关闭按钮是否点击
            listenMavonEditorMenuClose(){
                this.$nextTick(()=>{
                    let node= document.getElementsByClassName("v-note-navigation-close")[0];
                    node.addEventListener("click",()=>{
                        this.updateMenuStatus();
                    })
                })
            },
            //增加点击量
            addHitsNum(){
                this.request.get("/index/blog/addHitsNum",{
                    params:{
                        id:this.queryBlogId,
                    }
                }).then(res=>{
                    if (res.code=="200"){
                        this.blogHitsNum=res.data;
                    }
                })
            },
            //增加或者更新历史记录
            addOrUpdateHistory(){
                this.request.post("/index/history/addOrUpdateHistory",{
                    userId:localStorage.getItem("user")!=null?JSON.parse(localStorage.getItem("user")).id:null,
                    blogId:this.queryBlogId,
                    type: constants.historyType.visit,
                }).then(res=>{
                    if (res.code!="200"){
                        this.$message({
                            message: res.data,
                            type: 'warning'
                        });
                    }
                })
            },
            //通过id查询博客信息
            queryBlogById(){
                this.request.get("/index/blog/queryBlogById",{
                    params:{
                        id:this.queryBlogId,
                    }
                }).then(res=>{
                    if (res.code=="200"){
                        this.blog = res.data;
                        this.addCopyBtn();
                        this.addUrl();

                    }else if(res.code=="301"){
                        this.$message({
                            message: res.data,
                            type: 'warning'
                        });
                    }
                })
            },
            //改变blog的目录状态
            updateMenuStatus(){
                this.navigation=!this.navigation;

                if (!this.navigation){
                    document.getElementsByClassName("v-note-navigation-wrapper transition")[0]
                        .style.display = "none";
                    this.viewMenuTitle="打开导航栏";
                }else{
                    document.getElementsByClassName("v-note-navigation-wrapper transition")[0]
                        .style.display = "";
                    this.viewMenuTitle="关闭导航栏";
                }

            },
            // 复制代码函数
            shareCopy(codeText) {
                let that=this;
                let isSuccess = false; // 添加一个标志位，用于判断是否已经执行过success回调
                let clipboard = new Clipboard('.code-copy', {
                    text: function() {
                        return codeText
                    }
                })
                clipboard.on('success', e => {
                    if (!isSuccess){
                        // 复制成功
                        that.$message({
                            message: '复制成功',
                            type: 'success'
                        });
                        isSuccess=true;
                        e.clearSelection();
                    }

                })
                clipboard.on('error', e => {
                    if (!isSuccess){
                        // 复制成功
                        that.$message({
                            message: '复制失败',
                            type: 'error'
                        });
                        isSuccess=true;
                        e.clearSelection();
                    }
                })
            },
            // 动态添加复制按钮以及复制方法（获取到文档content成功的时候调用此方法）
            addCopyBtn() {
                this.$nextTick(function () {
                    let that=this;
                    let content = document.getElementsByClassName('v-show-content')[0]
                    let precodes = content.getElementsByTagName('pre')
                    let arr = Array.from(precodes)
                    arr.forEach((element) => {
                        let btn = document.createElement('div')
                        btn.innerHTML = 'copy';
                        btn.setAttribute('class', 'code-copy')
                        btn.addEventListener('click', function(e) {
                            let code = e.target.parentElement.children[1] // code 标签
                            let codeText = code.innerText
                            // 复制函数
                            that.shareCopy(codeText);
                        })
                        element.insertBefore(btn, element.firstChild);
                    })
                })
            },
            // 自定义修改导航侧边栏
            addUrl() {
                this.$nextTick(function () {
                    let _aList = document.querySelectorAll(".v-note-navigation-content a");
                    for (let i = 0; i < _aList.length; i++) {
                        let _aParent = _aList[i].parentNode;
                        let _a = _aParent.firstChild;
                        if (!_a.id) continue; // 把不属于导航中的a标签去掉，否则会报错
                        let _text = _aParent.lastChild;
                        let text = _text.textContent;
                        _a.href = "#" + _a.id;
                        _a.innerText = text;
                        _aParent.removeChild(_text);
                        // _a.style.color = "red";
                    }
                });
            },
            //展示所有的标签的弹窗
            toShowAllLabelsDialog(dialogBlogInfo){
                this.dialogBlogLabels=dialogBlogInfo.labels;
                this.dialogTitle="查看所有标签";
                this.dialogVisible=true;
            },
            //跳转到BlogManage界面通过labelId查询博客
            queryBlog(label){
                this.$router.push({path:"/frontFramework/blogManage",query:{queryLabelId:label.id}});
            },

        }
    }
</script>

<style scoped>

    .editorStyle{
        max-height: 100%;
        min-height: 80vh;
        width: 100%;
    }

    /deep/ .hljs {
        color: #24292e;
        background: transparent;
        padding: 15px;

    }


    /deep/ .markdown-body pre {
        background: #dfdbdb54;

    }

    .myTag{
        cursor: pointer;
        min-width: 46px;
        margin: 0 0 0 5px;
        width: 100%;
        text-align: center;
    }

    .labelLayout{
        flex: 1;
        text-align: center;
        height: 41px;
        margin-left: 20px;
    }




    /deep/ .v-note-wrapper .v-note-panel .v-note-navigation-wrapper {
        display: -webkit-box;
        display: -webkit-flex;
        display: -ms-flexbox;
        display: flex;
        position: absolute;
        width: 250px;
        right: 25px;
        top: 0;
        bottom: 0;
        height: 100%;
        -webkit-box-orient: vertical;
        -webkit-box-direction: normal;
        -webkit-flex-direction: column;
        -ms-flex-direction: column;
        flex-direction: column;
        background-color: rgba(255,255,255,0.98);
        border-left: 1px solid #f2f6fc;
        border-right: 1px solid #f2f6fc;
    }

    /deep/ .el-card.is-always-shadow, .el-card.is-hover-shadow:focus, .el-card.is-hover-shadow:hover {
        box-shadow: 0 2px 12px 0 rgba(242, 231, 231, 0.1);
    }

    .button-card{
        text-align: center;
    }

    /deep/  .code-copy {
        padding: 0 10px;
        background: #FFFFFF;
        border: 1px solid #5592E5;
        border-radius: 2px;
        font-size: 14px;
        color: #5592E5;
        cursor: pointer;
        display: inline-block;
        float: right;
    }

    /deep/ .v-note-wrapper .v-note-panel .v-note-navigation-wrapper.transition {
        transition: all 0.1s linear 0s;
        position: fixed;
        right: 19%;
        top: 18%;
        height: 70%;
    }

    /*.commentArea{*/
    /*    width: 100%;*/
    /*    min-height: 100px;*/
    /*    margin-top: 10px;*/
    /*}*/








</style>